package com.cardone.platform.controller;

import com.cardone.common.util.ReturnDataUtils;
import com.cardone.context.ContextHolder;
import com.cardone.platform.common.dto.EntityFileDto;
import com.cardone.platform.common.util.EntityFileUtils;
import com.google.code.kaptcha.Constants;
import com.google.common.collect.Maps;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * 健康管理平台首页
 *
 * @author yaohaitao
 */
@Setter
@Slf4j
@Controller
public class CommonController {
    @RequestMapping(value = {"/validationCode.jpg"})
    public void loginValidationCode(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        final String capText = ContextHolder.getBean(com.google.code.kaptcha.Producer.class).createText();

        SecurityUtils.getSubject().getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        final BufferedImage bi = ContextHolder.getBean(com.google.code.kaptcha.Producer.class).createImage(capText);

        try (java.io.OutputStream out = response.getOutputStream()) {
            ImageIO.write(bi, "jpg", out);

            out.flush();
        }
    }

    /**
     * 所有json请求
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/**/*.json"})
    @ResponseBody
    public Callable<String> allJson(final HttpServletRequest request) {
        String servletPath = com.cardone.common.util.WebUtils.getServletPath(request);

        String method = request.getMethod();

        return () -> com.cardone.platform.configuration.util.SiteUtils.fromJsonForReturnData(request, servletPath, method);
    }

    /**
     * 上传界面
     *
     * @return 上传界面模板路径
     */
    @RequestMapping(value = {"upload.txt", "upload.html"})
    @ResponseBody
    public String uploadTxt(final HttpServletRequest request, final HttpServletResponse response, EntityFileDto uploadEntityFile) throws Exception {
        if (StringUtils.isBlank(uploadEntityFile.getName())) {
            uploadEntityFile.setName("upload");
        }

        if (StringUtils.isBlank(uploadEntityFile.getThumbnailsTypeCode())) {
            uploadEntityFile.setThumbnailsTypeCode("miniImg");
        }

        final List<EntityFileDto> entityFileList = EntityFileUtils.upload(request, uploadEntityFile);

        if (CollectionUtils.isEmpty(entityFileList)) {
            return com.cardone.common.util.MapperUtils.toJson(Maps.newHashMap());
        }

        String editorid = request.getParameter("editorid");

        if (StringUtils.isNotBlank(editorid)) {

            Map<String, Object> map = Maps.newHashMap();

            EntityFileDto entityFile = entityFileList.get(0);

            map.put("originalName", entityFile.getOriginalFilename());
            map.put("name", entityFile.getFilename());
            map.put("url", entityFile.getFilename());
            map.put("size", entityFile.getSize());
            map.put("type", entityFile.getExtension());
            map.put("state", "SUCCESS");

            return com.cardone.common.util.MapperUtils.toJson(map);
        }

        List<Map<String, Object>> mapList = ContextHolder.getBean(org.dozer.Mapper.class).map(entityFileList, List.class, "entityFileDtoToMap-2");

        Map<String, Object> map = ReturnDataUtils.newMap(mapList);
        map.put("success", "true");

        return com.cardone.common.util.MapperUtils.toJson(map);
    }


    /**
     * 上传界面
     *
     * @return 上传界面模板路径
     */
    @RequestMapping(value = {"uploadByValidation.txt"})
    @ResponseBody
    public String uploadByValidationTxt(final HttpServletRequest request, final HttpServletResponse response, EntityFileDto uploadEntityFile) throws Exception {
        if (StringUtils.isEmpty(uploadEntityFile.getValidationCode())) {
            throw new CodeException("验证码不能为空");
        }

        String capText = (String) SecurityUtils.getSubject().getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

        if (!StringUtils.equalsIgnoreCase(capText, uploadEntityFile.getValidationCode())) {
            throw new CodeException("验证码输入不正确");
        }

        return this.uploadTxt(request, response, uploadEntityFile);
    }


    /**
     * 所有html请求
     *
     * @param request
     */
    @RequestMapping(value = {"/login.html"})
    public void loginHtml(final HttpServletRequest request) {
        Boolean isLoginError = (Boolean) SecurityUtils.getSubject().getSession().getAttribute("isLoginError");
        request.setAttribute("isLoginError", BooleanUtils.isTrue(isLoginError) ? 1 : 0);
    }

    /**
     * 所有html请求
     *
     * @param request
     */
    @RequestMapping(value = {"/**/*.html", "", "/"})
    public void allHtml(final HttpServletRequest request) {
        com.cardone.platform.configuration.util.SiteUtils.fillData(request);
    }
}
